package com.ajou.adonate.filemgr;


import java.io.*;
import java.util.ArrayList;

public class FileSplit {
	private File file;
	private int fileSplitSize, fileCount;
	private byte[][] splitFileByte;
	private ArrayList<String> fileList = new ArrayList<String>();
	
	public FileSplit(String path, String fileName, int splitSize) {
		file = new File(path, fileName);
		fileSplitSize = splitSize;
		fileCount = (int) ((file.length()-1) / fileSplitSize) + 1;
		
		splitToFileByte();
	}
	
	public void setFileSize (int splitSize) {
		fileSplitSize = splitSize;
	}
	
	public void splitToFileByte() {		
		splitFileByte = new byte[fileCount][];
		
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bin = new BufferedInputStream(fis);
			
			for (int i=0; i<fileCount; i++) {
				if (fileCount == i+1) {
					splitFileByte[i] = new byte[(int)(file.length()) - fileSplitSize*(fileCount-1)];
					bin.read(splitFileByte[i], 0, (int)(file.length()) - fileSplitSize*(fileCount-1));
				} else {
					splitFileByte[i] = new byte[fileSplitSize];
					bin.read(splitFileByte[i], 0, fileSplitSize);
				}
			}			
			
			fis.close();
			bin.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public byte[] getSplitFileByte(int index) {
		return splitFileByte[index];
	}
	
	public int getFileCount() {
		return fileCount;
	}
	
	public ArrayList<String> getFileList() {
		return fileList;
	}
	
	public void byteToFile(String path, String fileName) {
		try {
			if (fileCount == 1) {
				File f = new File(path, fileName);
				
				FileOutputStream fos = new FileOutputStream(f);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				fileList.add(path+fileName);
				bos.write(splitFileByte[0]);
				bos.close();
				fos.close();
			} else {
				for (int i=0; i<fileCount; i++) {
					File f = new File(path, fileName + ".spl" + i);
					
					FileOutputStream fos = new FileOutputStream(f);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					fileList.add(path+fileName + ".spl" + i);
					bos.write(splitFileByte[i]);
					bos.close();
					fos.close();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}